class Request {
  config = {
    baseUrl: '',
    uploadUrl: '',
    header: {
      'content-type': 'application/json',
	  'token': uni.getStorageSync('token')
    },
    method: 'GET',
    dataType: 'json',
    interceptorAllData: false,
    timeout: 10000,
    // #ifndef MP-ALIPAY || APP-PLUS
    responseType: 'text',
    // #endif

    // #ifdef MP-ALIPAY
    // timeout: 10000,
    // #endif

    // #ifdef APP-PLUS
    sslVerify: true,
    // #endif

    // #ifdef H5
    withCredentials: false,
    // #endif
  }

  setConfig(configs) {
    this.config = {
      ...this.config,
      ...configs,
    }
  }

  /* 判断url是否为绝对路径 */
  static absUrl(url) {
    return /(http|https):\/\/([\w.]+\/?)\S*/.test(url)
  }

  interceptor = {
    /**
     *  请求之前拦截
     */
    request: (cb) => {
      if (cb) {
        this.requestBeforeFun = cb
      }
    },
    /**
     * @param {Request~responseSuccessCallback} success 响应拦截器，对响应数据做点什么
     * @param {Request~responseErrorCallback} error 响应拦截器，对响应错误做点什么
     */
    response: (success, error) => {
      if (success && error) {
        this.requestSuccessFun = success
        this.requestErrorFun = error
      }
    },
  }
  //请求前处理
  requestBeforeFun(type, config) {
    return config
  }
  //成功处理
  requestSuccessFun(type, response) {
    return response
  }
  //错误处理
  requestErrorFun(type, error) {
    return error
  }

  request(options = {}) {

    options.baseUrl = this.config.baseUrl
    options.dataType = options.dataType || this.config.dataType

    // #ifndef MP-ALIPAY || APP-PLUS
    options.responseType = options.responseType || this.config.responseType
    // #endif

    // #ifdef MP-ALIPAY
    options.timeout = options.timeout || this.config.timeout
    // #endif

    options.url = options.url || ''
    options.data = options.data || {}
    options.params = options.params || {}

    options.header = {
      ...this.config.header,
      ...options.header,
    }
    options.method = options.method || this.config.method

    // #ifdef APP-PLUS
    options.sslVerify =
      options.sslVerify === undefined
        ? this.config.sslVerify
        : options.sslVerify
    // #endif

    // #ifdef H5
    options.withCredentials =
      options.withCredentials === undefined
        ? this.config.withCredentials
        : options.withCredentials
    // #endif

    //请求之前拦截
    let beforeData = this.requestBeforeFun('request', options)
    if (beforeData === false) {
      return new Promise(() => {})
    }
    options = beforeData
    uni.showLoading({
      title: '加载中',
    })
    return new Promise((resolve, reject) => {
      options.complete = (response) => {
        // 当天日期超过2024-01-01跳转登录
        // let date = new Date();
        // let year = date.getFullYear();
        // let month = date.getMonth() + 1;
        // let day = date.getDate();
        // let nowDate = year + '-' + month + '-' + day;
        // if (nowDate > '2023-12-30') {
        //   uni.navigateTo({
        //     url: '/pages/login/login'
        //   })
        //   return
        // }
        if (response.statusCode == 401) {
			uni.showToast({
				title: response.data.reason,
				icon: 'none'
			})
          uni.hideLoading()
          uni.navigateTo({
            url: '/pages/login/login'
          });
          return
        }
        if (response.statusCode == 200) {
          // 成功
          uni.hideLoading()
          //是否全部拦截
          response = this.requestSuccessFun(
            'request',
            this.config.interceptorAllData ? response : response.data
          )
          resolve(response)
        } else {
          uni.hideLoading()
          //是否全部拦截
          response = this.requestErrorFun(
            'request',
            this.config.interceptorAllData ? response : response.data
          )
          reject(response)
        }
      }
      options.url = Request.absUrl(options.url)
        ? options.url
        : options.baseUrl + options.url
      uni.request(options)
    })
  }

  get(url, data = {}, options = {}) {
    return this.request({
      url,
      data,
      method: 'GET',
      ...options,
    })
  }

  post(url, data = {}, options = {}) {
    return this.request({
      url,
      data,
      method: 'POST',
      ...options,
    })
  }

  upload(
    url,
    {
      // #ifdef APP-PLUS || H5
      files,
      // #endif
      // #ifdef MP-ALIPAY
      fileType,
      // #endif
      filePath,
      name,
      formData,
    }
  ) {
    const uploadHeader = {
      ...this.config.header,
    }
    delete uploadHeader['Content-Type']
    let options = {
      baseUrl: this.config.uploadUrl,
      url,
      // #ifdef APP-PLUS
      files,
      // #endif
      // #ifdef MP-ALIPAY
      fileType,
      // #endif
      filePath,
      method: 'UPLOAD',
      name,
      header: {
        ...uploadHeader,
      },
      formData,
    }

    //上传之前拦截
    let beforeData = this.requestBeforeFun('request', options)
    if (beforeData === false) {
      return new Promise(() => {})
    }
    uni.showToast({
      title: '上传中...',
      icon: 'loading',
    })
    return new Promise((resolve, reject) => {
      options.complete = (response) => {
		  console.log('response')
        uni.hideToast()
        if (response.statusCode == 200) {
          // 成功
          //是否全部拦截
          response = this.requestSuccessFun(
            'upload',
            this.config.interceptorAllData ? response : response.data
          )
          resolve(response)
        } else {
          //是否全部拦截
          response = this.requestErrorFun(
            'upload',
            this.config.interceptorAllData ? response : response.data
          )
          reject(response)
        }
      }
      options.url = Request.absUrl(options.url)
        ? options.url
        : options.baseUrl + options.url
      uni.uploadFile(options)
    })
  }
}
export default new Request()
